<template>
	<view>
		<view class="goshop-list-wrap">
			<u-toast ref="uToast"></u-toast>
			<view class="goshop-list-item goshop-list-item-bottom" >
				<view class="goshop-list-item-left">
					{{avatarText}}
				</view>
				<view class="goshop-list-item-right">
					<u-upload
						width="40"
						height="40"
						:fileList="fileList"
						@afterRead="afterRead"
						@delete="deletePic"
						:maxCount="1"
					></u-upload>
					<view class="iconfont iconfont-right_arrow icon-bg-color u-m-l-10"></view>
				</view>
			</view>
			<view class="goshop-list-item goshop-list-item-bottom" @tap="goAuthPage()">
				<view class="goshop-list-item-left">
					{{membernameText}}
				</view>
				<view class="goshop-list-item-right">
					{{memberInfo.username}}
				</view>
			</view>
			<view class="goshop-list-item goshop-list-item-bottom" @tap="$Router.push({ path: '/pages/common/update/nick_name', query: { nick_name: memberInfo.nickname} })">
				<view class="goshop-list-item-left">
					{{nicknameText}}
				</view>
				<view class="goshop-list-item-right">
					{{memberInfo.nickname}}
					<view class="iconfont iconfont-right_arrow icon-bg-color u-m-l-10"></view>
				</view>
			</view>
			<view class="goshop-list-item goshop-list-item-bottom" @tap="sexShow = true">
				<view class="goshop-list-item-left">
					{{genderText}}
				</view>
				<view class="goshop-list-item-right">
					{{sexText}}
					<view class="iconfont iconfont-right_arrow icon-bg-color u-m-l-10"></view>
				</view>
			</view>
			<view class="goshop-list-item goshop-list-item-bottom" @tap="birthdayShow = true">
				<view class="goshop-list-item-left">
					{{birthdayText}}
				</view>
				<view class="goshop-list-item-right">
					{{memberInfo.birthday}}
					<view class="iconfont iconfont-right_arrow icon-bg-color u-m-l-10"></view>
				</view>
			</view>
			<view class="goshop-list-item goshop-list-item-bottom" @tap="showArea = true" v-if="locale ==='zh-Hans'">
				<view class="goshop-list-item-left">
					{{areaText}}
				</view>
				<view class="goshop-list-item-right">
					{{memberInfo.provinceName}}
					<view class="iconfont iconfont-right_arrow icon-bg-color u-m-l-10"></view>
				</view>
			</view>
			<view class="goshop-list-item goshop-list-item-bottom" @tap="$Router.push({ path: '/pages/common/update/introduction', query: { intro: memberInfo.intro ? memberInfo.intro:''} })">
				<view class="goshop-list-item-left">
					{{introductionText}}
				</view>
				<view class="goshop-list-item-right">
					{{memberInfo.intro}}
					<view class="iconfont iconfont-right_arrow icon-bg-color u-m-l-10"></view>
				</view>
			</view>
		</view>
		<u-action-sheet :actions="sexActions" @close="selectSexClose" @select="selectSexClick" :closeOnClickOverlay="true" :closeOnClickAction="true"  :title="sexTitle" :show="sexShow"></u-action-sheet>
			<u-datetime-picker
			    ref="datetimePicker"
				:show="birthdayShow"
				:value="memberInfo.birthday"
				mode="date"
				:formatter="formatter"
				:minDate="minDate"
				:maxDate="currentDate"
				closeOnClickOverlay
				@confirm="doUpdateBirthday"
				@cancel="birthdayClose"
				@close="birthdayClose"
				:cancelText="cancelText"
				:confirmText="confirmText"
			></u-datetime-picker>
		 <u-picker :show="showArea" @cancel="showArea=false" ref="uPicker" class="uPicker" :columns="addressColumns" @confirm="addressConfirm" @change="changeHandler" :defaultIndex="defaultAddress"></u-picker>
	</view>
</template>

<script>
	import {updateAvatar,updateSex,updateBirthday,updateArea} from '@/common/http.api.js'
	import { mapState, mapActions, mapGetters } from 'vuex';
	import config from '@/common/config.js'
	import city from '@/utils/area';
	export default {
		data() {
			return {
				defAvatar: '',
				fileList: [],
				sexTitle:'',
				birthdayShow:false,
				sexShow:false,
				sexActions:[
					{
						name: this.$t('common.male.text'),
						type:1
					},
					{
						name: this.$t('common.female.text'),
						type:2
					},
				],
				showArea:false,
				defaultAddress: [],
				addressColumns: [],
				addressData:[],
				avatarText:'',
				membernameText:'',
				nicknameText:'',
				genderText:'',
				updatesuccessText:'',
				birthdayText:'',
				areaText:'',
				introductionText:'',
				updatefailText:'',
				locale:'',
				femaleText:'',
				sexText:'',
				uploadloadingText:'',
				cancelText:'',
				confirmText:'',
				minDate: -1262332800,
				currentDate:new Date().getTime()
			};
		},
		computed: {
			...mapGetters(['memberInfo'])
		},
		onReady() {
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		async onLoad(){
			this.handleArea();
			await this.$onLaunched;
			this.initData();
		},
		async onShow(){
		  await this.getMemberInfo();
		  this.fileList = [];
		  this.fileList.push( {
		  		status: 'success',
		  		message: '',
		  		url: this.memberInfo.avatar
		  });
		  this.refresh();
		  this.locale = this.$i18n.locale;
		},
		methods:{
			...mapActions(['getMemberInfo']),
			refresh(){
				this.sexTitle = this.$t('common.selectgender.text');
				this.avatarText = this.$t('common.avatar.text');
				this.membernameText = this.$t('material.membername.text');
				this.nicknameText = this.$t('material.nickname.text');
				this.genderText = this.$t('material.gender.text');
				this.birthdayText = this.$t('material.birthday.text');
				this.introductionText = this.$t('material.introduction.text');
				this.areaText = this.$t('material.area.text');
				this.maleText = this.$t('common.male.text');
				this.femaleText = this.$t('common.female.text');
				this.updatesuccessText = this.$t('common.updatesuccess.text');
				this.updatefailText = this.$t('common.updatefail.text');
				this.uploadloadingText = this.$t('common.uploadloading.text');
				this.cancelText = this.$t('common.cancel.text');
				this.confirmText = this.$t('common.sure.text');
				if(this.memberInfo.sex === 1){
					this.sexText = this.maleText;
				}else{
					this.sexText = this.femaleText;
				}
			},
			goAuthPage(){
				let locale = this.$i18n.locale;
				if(locale === 'zh-Hans'){
					uni.navigateTo({
						url: "/pages/common/auth/zh_auth",
					})
				}else{
					uni.navigateTo({
						url: "/pages/common/auth/en_auth",
					})
				}
			},
			initData(){
				this.defAvatar = this.$store.state.$appInfo.defaultAvatar;
			},
			handleArea(){
				let {
					provinceData,
						cityData,
						areaData
					} = city;
				let arr=[];
				let province=[];
				let arr1=[];
				let arr2=[];
				provinceData.forEach((item, index) => {
					arr.push({
						...item,
						children: []
					});
					arr[index].children.push(...cityData[index]);
					arr[index].children.forEach((item1, index1) => {
						item1['children'] = [];
						item1.children.push(...areaData[index][index1]);
						
					});
				});
				province=arr.map(e=>{return e.label});
				arr1=arr[0].children.map(e=>{return e.label});
				arr2=arr[0].children[0].children.map(e=>{return e.label});
				this.addressColumns=[province,arr1,arr2]
				this.addressData=arr;
			},
			changeHandler(e) {
				const {
						columnIndex,
						value,
						values, // values为当前变化列的数组内容
						index,
						indexs,
						// 微信小程序无法将picker实例传出来，只能通过ref操作
						picker = this.$refs.uPicker
					} = e
					// 当第一列值发生变化时，变化第二列(后一列)对应的选项
					if (columnIndex === 0) {
						// picker为选择器this实例，变化第二列对应的选项
						let children1=this.addressData[index].children.map(e=>{return e.label})
						picker.setColumnValues(1, children1)
						// console.log(this.addressData[index].children[indexs[1]].children)
						let children2=this.addressData[index].children[indexs[1]].children.map(e=>{return e.label})
						picker.setColumnValues(2, children2)
					}
					if (columnIndex === 1) {
						// console.log("index",index,"indexs",indexs)
						let children3=this.addressData[indexs[0]].children[indexs[1]].children.map(e=>{return e.label})
						picker.setColumnValues(2, children3)
					}
			},
			addressConfirm(e) {
				let that = this;
				this.showArea=false;
				this.memberInfo.provinceName = e.value[0];
				this.memberInfo.area=`${e.value[0]}-${e.value[1]}-${e.value[2]}`
				updateArea({params: {area: this.memberInfo.area}}).then(res => {
					if (res.code === 0) {
						this.$refs.uToast.show({
							message: that.updatesuccessText,
							type: 'success'
						})
						uni.hideLoading();
					} else {
						uni.hideLoading();
						uni.showModal({
							showCancel: false,
							title: that.updatefailText,
							content: res.msg,
						});
					}
				});
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}`
				}
				if (type === 'month') {
					return `${value}`
				}
				if (type === 'day') {
					return `${value}`
				}
				return value
			},
			fmtDate(obj){
			        var date =  new Date(obj);
			        var y = 1900+date.getYear();
			        var m = "0"+(date.getMonth()+1);
			        var d = "0"+date.getDate();
			        return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
			},
			birthdayClose() {
				this.birthdayShow = false
			},
			doUpdateBirthday(date){
				debugger
				let dt = this.fmtDate(date.value);
				let that = this;
				updateBirthday({params: {birthday: dt}}).then(res => {
					if (res.code === 0) {
						this.birthdayShow = false;
						this.memberInfo.birthday = dt;
						this.$refs.uToast.show({
							message: that.updatesuccessText,
							type: 'success'
						})
						uni.hideLoading();
					} else {
						uni.hideLoading();
						uni.showModal({
							showCancel: false,
							title: that.updatefailText,
							content: res.msg,
						});
					}
				});
			},
			selectSexClick(index){
				let that = this;
				updateSex({params: {sex: index.type}}).then(res => {
					if (res.code === 0) {
						this.memberInfo.sexName = index.name;
						this.sexText = index.name;
						this.$refs.uToast.show({
							message: that.updatesuccessText,
							type: 'success'
						})
						uni.hideLoading();
					} else {
						uni.hideLoading();
						uni.showModal({
							showCancel: false,
							title: that.updatefailText,
							content: res.msg,
						});
					}
				});
			},
			selectSexClose(){
			    this.sexShow = false;
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				let that = this;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: that.uploadloadingText
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let json = JSON.parse(result);
					if(json.code === 0){
						this.memberInfo.avatar = json.data;
						let item = this.fileList[fileListLen]
						this.fileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: json.data
						}))
						fileListLen++
					}
				}
				updateAvatar({params: {avatar: this.memberInfo.avatar}}).then(res => {
					if (res.code === 0) {
						this.$refs.uToast.show({
							message: that.updatesuccessText,
							type: 'success'
						})
						uni.hideLoading();
					} else {
						uni.hideLoading();
						uni.showModal({
							showCancel: false,
							title: that.updatefailText,
							content: res.msg,
						});
					}
				});
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/app/common/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							"tenant-id": config.tenantId //token校验
						},
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data)
							}, 1000)
						},
						complete: (res)=>{
							let json = JSON.parse(res.data);
							if(json.code != 0){
								this.fileList.splice(this.fileList.length-1, 1)
								this.$refs.uToast.show({
									message: json.msg,
									type: 'error',
								})
							}
						}
					});
				})
			},
		}
	}
</script>

<style lang="scss">
.goshop-list-item-right{
	display: flex;
	align-items: center;
}
/deep/ .u-upload__button{
	margin:0 !important;
}
/deep/ .u-upload__wrap__preview{
	margin:0 !important;
}
</style>
